﻿using System;
using System.Linq;
using System.Net.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.HttpClients;

namespace User.Api.Models
{
    public class CardService
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CardService));

        /// <summary>
        /// 扫描二维码绑卡
        /// </summary>
        /// <param name="sceneId">二维码场景Id</param>
        /// <param name="openId">微信openId</param>
        /// <param name="card">就诊卡</param>
        /// <returns>
        /// 返回值：-1 获取用户信息失败， 0 绑卡成功，1 超出最大绑卡数量， 2 重复绑卡， 3 二维码场景Id无效
        /// </returns>
        public static int BindCardByScan(long sceneId, string openId, out HospCard card)
        {
            card = null;
            var cardNo = "";
            var cardType = -1;
            long userId = 0;

            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var user = ctx.WxUsers.FirstOrDefault(x => x.OpenId == openId);
                if (user == null)
                {
                    return -1;
                }
                userId = user.Id;
                var sceneInfo = ctx.SceneInfoes.FirstOrDefault(x => x.Id == sceneId);
                if (sceneInfo != null)
                {
                    cardNo = sceneInfo.CardNo;
                    //诊疗卡
                    if (cardNo.Length == 10)
                    {
                        cardType = 0;
                    }
                    //健康卡
                    else if (cardNo.Length == 16)
                    {
                        cardType = 1;
                    }
                    //市民卡
                    else if (cardNo.Length == 19)
                    {
                        cardType = 2;
                    }
                }
            }

            if (cardNo != "" && cardType != -1)
            {
                var cardMax = -1;
                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    var hospSetting = ctx.HospSettings.FirstOrDefault(x => x.Key == "CardMax" && x.RecStatus == 1);
                    var hospDefaultSetting = ctx.HospSettingVars.FirstOrDefault(x => x.Key == "CardMax" && x.RecStatus == 1);

                    if (hospDefaultSetting.IsNotNull())
                    {
                        cardMax = hospDefaultSetting.DefaultValue.ToInt32OrDefault(-1);
                    }

                    if (hospSetting.IsNotNull())
                    {
                        cardMax = hospSetting.Value.ToInt32OrDefault(-1);
                    }
                }

                if (cardMax != -1)
                {
                    using (var ctx = new GdsfybjyWeiXinEntities())
                    {
                        var model = ctx.HospCards.Where(x => x.WxUserId == userId && x.CardStatus == 1 && x.DeleteStatus == 0).ToList();
                        if (model.Count() >= cardMax)
                        {
                            return 1;// new { IsSucceed = false, ErrMsg = "最多可以添加" + cardMax + "张就诊卡!" };
                        }
                    }
                }

                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    var model = ctx.HospCards.FirstOrDefault(x => x.CardType == cardType && x.CardNo.Trim() == cardNo.Trim()
                        && x.WxUserId == userId
                        && x.CardStatus == 1 && x.DeleteStatus == 0);
                    if (model != null)
                    {
                        return 2;// new { IsSucceed = false, ErrMsg = "您已经添加过此就诊卡，请不要重复添加" };
                    }
                }

                //获取院内webservice
                var getPatientRequest = new GetPatientInfoRequest();
                getPatientRequest.CardNo = cardNo;

                GetPatientInfoResponse getPatientResponse;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetPatientInfo", getPatientRequest).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    getPatientResponse = responseMsg.Content.ReadAsAsync<GetPatientInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                    return -1;
                }

                if (getPatientResponse.ResultCode != "0")
                {
                    return -1;
                }

                var patientInfo = getPatientResponse;

                var patientName = getPatientResponse.PatientInfo.Name.Trim();

                var setDefault = "true";

                var hospCardModel = new HospCard
                {
                    //OpenId = openId,
                    WxUserId = userId,
                    CardType = cardType,
                    CardNo = cardNo.Trim(),
                    PatientName = patientName.Trim(),
                    CardStatus = 1,
                    AddDt = DateTime.Now,
                    UpdateDt = DateTime.Now,
                    DeleteStatus = 0,
                    PatientId = patientInfo.PatientInfo.PatientId.Trim(),
                    InDeptNo = patientInfo.PatientInfo.InpatientNo.Trim(),
                    Name = patientInfo.PatientInfo.Name.Trim(),
                    Gender = patientInfo.PatientInfo.Gender.Trim(),
                    Birthdate = patientInfo.PatientInfo.Birthdate.Trim(),
                    IdenNo = patientInfo.PatientInfo.IdenNo.Trim(),
                    Phone = patientInfo.PatientInfo.Phone.Trim(),
                    IsDefault = setDefault == "true" ? 1 : 0
                };

                if (setDefault == "true")
                {
                    using (var ctx = new GdsfybjyWeiXinEntities())
                    {
                        var cards = ctx.HospCards.Where(x => x.WxUserId == userId).ToList();
                        foreach (var hospCard in cards)
                        {
                            hospCard.IsDefault = 0;
                        }
                        ctx.SaveChanges();
                    }
                }

                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    ctx.HospCards.Add(hospCardModel);
                    ctx.SaveChanges();
                }

                card = hospCardModel;
                return 0;
            }

            return 3;
        }
    }
}